﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using log4net;

namespace Entangle
{
    class RequestServiceHost
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(RequestServiceHost));

        private System.Threading.AutoResetEvent stopFlag = new System.Threading.AutoResetEvent(false);
        private bool _isRunning = false;

        public bool isRunning { get { return _isRunning; } }

        public void Start()
        {
            log.Info("Starting RequestServiceHost");
            Uri uri = new Uri("http://localhost:" + Properties.Settings.Default.PortNumber + "/RequestService");
            using (ServiceHost host = new ServiceHost(typeof(RequestService),uri))
            {
                log.Debug("Host created on: " + uri.ToString());
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                log.Debug("Opening host.");
                host.Open();
                _isRunning = true;
                log.Debug("Host opened.");

                stopFlag.WaitOne();

                log.Debug("Closing host.");
                _isRunning = false;
                host.Close();
                log.Debug("Host closed.");
            }
        }
        public void Stop()
        {
            stopFlag.Set();
        }
    }
}
